package nf.graph;

import java.util.*;
import nf.util.FilteringIterator;

public class DistinctGraphIterator extends FilteringIterator<Graph>
{
	private ArrayList<List<Graph>> sortedGraphs;
	private Comparator<Graph> gc;
	
	public DistinctGraphIterator(Iterator<Graph> inner)
	{
		this(inner, 5);
	}
	
	public DistinctGraphIterator(Iterator<Graph> inner, int nodeCount)
	{
		super(inner);
		
		int possibleEdges = nodeCount * (nodeCount - 1);
		sortedGraphs =	new ArrayList<List<Graph>>(possibleEdges + 1);
		gc = new IsomorphicComparator();
	}
	
	private List<Graph> getPossibles(int edgeCount)
	{
		int size = sortedGraphs.size();
		if (edgeCount >= size) {
			for (int i = size - 1; i < edgeCount; i++) {
				sortedGraphs.add(new LinkedList<Graph>());
			}
		}
		
		return sortedGraphs.get(edgeCount);
	}
	
	public boolean accept(Graph graph)
	{
		List<Graph> possibles = getPossibles((int) graph.edgeCount());
		
		for (Graph possible : possibles) {
			if (gc.compare(possible, graph) == 0) {
				return false;
			}
		}
		
		possibles.add(graph.copy());
		return true;
	}
}
